<?php
/**
 * Description of MainController
 *
 * @author Kopi
 */

abstract class MainController extends Controller {

    /**
     * @var User
     */
    protected $user;
    protected $userLoggedIn;
    private static $user_objects = array('MfUser','Performer','User','Agency');

    protected $tables = array();

    public function AdminLoginRedirectAction($param) {
	$this->AddRedirect(Router::GenerateUrl(array('login'=>'index')), 0);
    }

    public function adminRun($param) {
    }



    /**
     * Dodatkowy starter kontrolera
     *
     */
    protected function Run($param = array()) {

		if(Config::Get('site') == PageType::ADMIN) {
			$this->RunShared('LeftPanel', $param);
		} else {
			
		}
    }
    
    protected function PostRun($param) {
    	/*if(Config::Get('site') == PageType::STRONA) {
    		$this->RunShared('Header', $param);
			$this->RunShared('Footer', $param);
    	}*/
    }

    protected function Seo($class = __CLASS__, $method = __METHOD__) {


	$seoObj = WpSeoDAL::GetByType(WpSeo::GetMapByController($class.$method));
	if(isset($seoObj) && is_object($seoObj)) {
	    if($seoObj->getTitle()!='') {

		$this->AddTitle($seoObj->getTitle());
	    }
	    if($seoObj->getDescription()!='') {
		$this->AddDescription($seoObj->getDescription());
	    }
	    if($seoObj->getKeywords()!='') {
		$this->AddKeywords($seoObj->getKeywords());
	    }
	}
    }


    public function Error404Action($param) {
		$this->addDescription('Strona główna');
		$this->addTitle('Strona główna');
		echo '<pre>';
		var_dump(Router::$route);
		print '404';
		die;


 	//$this->SetAjaxRender();
	//$this->SetNoRender();
	//header("Status: 404 Not Found");

	//$this->content=file_get_contents('error.html');
	//include("error.html");
	//header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found");
    //$this->AddRedirect('error.html', 0);
    //$this->AddRedirect(Router::GenerateUrl(array('_value'=>'error')), 0, 301);
    }

    /**
     * informacjay o przekierowaniu
     *
     * @param string $url
     * @param string $info
     */
    protected function AddRedirectInfo($info,$type = null,$url = null,$jsRedirect = false) {
		SessionProxy::SetValue("frameInfo", $info);
		if($type != null) {
			SessionProxy::SetValue("frameType", $type);
		}
	
	
		if($url != null && $jsRedirect == false)
			$this->AddRedirect($url, -1);
		else if($url != null)
			$this->content = "document.location.href='$url';";

    }

    /**
     * PObranie informacji o przekierowaniu
     *
     */
    private function GetRedirectInfo() {
	if(SessionProxy::GetValue("frameInfo")!= "") {
	    $this->RunShared('InfoFrame', array('type'=>SessionProxy::GetValue('frameType'),'info'=>SessionProxy::GetValue("frameInfo")));

	    SessionProxy::ClearValue('frameType');
	    SessionProxy::ClearValue('frameInfo');
	}

    }

   
    /**
     * Weryfikacja czy user jest zalogowany
     *
     * @return boolean
     */
    public function IsUser() {
	if(is_object($this->user)) {

	    return true;
	} else {
	    return false;
	}
    }

    protected function UserSession() {
	if($this->user) {
	    $id = $this->user->GetId();
	    if(!empty($id) && (int)$id > 0) {
		ActiveChecker::Touch($id);
	    }
	}
    }

    protected function RemoveUserSession() {
	if($this->user) {
	    $id = $this->user->GetId();
	    if(!empty($id) && (int)$id > 0) {
		ActiveChecker::Remove($id);
	    }
	}
    }

    protected function FormatAjaxOutput($errors, $param) {
	$out = array();
	$validateField = null;
	if(Request::Check('validate'))$validateField = Request::GetPost('validate');
	if(isset($param['redirect']) && !isset($param['field'])) {
	    $out['redirect'] = $param['redirect'];
	}
	if(empty($errors)) {
	    $out['success'] = true;
	} else {
	    $out['fields'] = array();
	    foreach($errors as $row) {
		if(isset($param['field'])) {
		    if($param['field'] == $row['field'] || $row['field'] == urldecode($param['field'])) {
			$out['fields'][$param['field']] = $row;
		    }elseif($validateField == $row['field']) {
			$out['fields'][$validateField] = $row;
		    }
		} else {
		    $out['fields'][$row['field']] = $row;
		}
	    }
	    if(!empty($out['fields'])) {
		$out['success'] = false;
	    } else {
		$out['success'] = true;
	    }
	}
	if(isset($param['msg'])) {
	    $out['msg'] = $param['msg'];
	}
	if(isset($param['hide'])) {
	    $out['hide'] = $param['hide'];
	}
	return json_encode($out);
    }

    public final function GeneratePopover($title, $image, $message, $buttons,$inputText = false) {
	$this->SetAjaxRender(true);
	//$this->partialTemplate = '../Popover/PopoverSmall.tpl';
	$this->smarty->assign('popoverButtons', $buttons);
	$this->smarty->assign('popoverTitle', $title);
	$this->smarty->assign('popoverImage', $image);
	$this->smarty->assign('popoverMessage', $message);
	$this->smarty->assign('popoverInputText', $inputText);

	return $this->smarty->fetch('partial/Popover/PopoverSmall.tpl');

    }

    public function GetDictionary($keyword,$replacement = array()) {
	$dictionaryArray = Registry::Get("dictionary");
	return vsprintf($dictionaryArray[$keyword], $replacement);
    }

    private function LoadDictionary($lang = "pl") {
	Registry::Set("dictionary",MfDictionaryDAL::GetAllVariables($lang,36000) );
    }
	/*
	 * tłumaczenie słownika
	 */
	protected function T($label,$param = array())
	{
		return Utils::Translate($label,$this->user,$param);
	}

    public static function GenerateTagCloud($tagsArray) {
	$minFontSize = 1;
	$maxFontSize = 7;
	$stepB=1;
	$limit = 0;
	$newArray = array();

	for ($i=0; $i < count($tagsArray); $i++) {

	    $arrayObj[] = $tagsArray[$i];
	    $counterValues[] = $tagsArray[$i]->GetCounter();
	}
	if(isset($arrayObj)) {

	    $maxCounterValue = max(array_values($counterValues));
	    $minCounterValue = min(array_values($counterValues));


	    $spread = $maxCounterValue - $minCounterValue;

	    if ($spread==0) { $spread = 1; }
	    $step = ($maxFontSize - $minFontSize) / $spread;



	    $count = count($arrayObj);


	    //$randomKeys = array_rand($arrayObj, $limit);

	    for($i=0; $i < $count; $i++) {
		$size = round($minFontSize + (($arrayObj[$i]->GetCounter() - $minCounterValue) * $step));

		$arrayObj[$i]->SetFontSize($size);
		$newArray[] = $arrayObj[$i];
	    }

	    return $newArray;
	}
    }

    public function checkAccess($resource, $default = false, $user = null) {
    	if(is_null($user)) {
    		$user = $this->user;
    	}
    	
    	if(is_null($user)) {
    		return $default;
    	}
    	
    	return $user->checkAccess($resource, $default);
    }

	public function RestrictedAccess($param, $role = null){
		
		if(is_null($role) || (!is_string($role) && !is_array($role)))
		    return false;

		if(!$this->userLoggedIn && ((is_string($role) && $role == 'guest') || (is_array($role) && in_array('guest',$role)))) {
			return false;
		}

		if((is_object($this->user) && in_array(get_class($this->user), array_keys(MfUser::$available_classes)) && $this->user->hasRole($role))) {
			
			Router::CleanUrlHistory();
			
			$savedPost = unserialize(SessionProxy::GetValue('login_fail_saved_post'));
			$savedGet  = unserialize(SessionProxy::GetValue('login_fail_saved_get'));
			$savedFile = unserialize(SessionProxy::GetValue('login_fail_saved_file'));
			
			SessionProxy::ClearValue('login_fail');
			SessionProxy::ClearValue('login_fail_saved_post');
			SessionProxy::ClearValue('login_fail_saved_get');
			SessionProxy::ClearValue('login_fail_saved_file');

			if(is_array($savedPost))foreach($savedPost AS $k => $row)$_POST[$k]  = $row;
			if(is_array($savedGet ))foreach($savedGet  AS $k => $row)$_GET[$k]   = $row;
			if(is_array($savedFile))foreach($savedFile AS $k => $row)$_FILES[$k] = $row;
			
			return false;
		}/*else if(in_array(get_class($this->user), self::$user_objects)){
			
		}*/else {
			
			$loginFail = SessionProxy::IsSetValue('login_fail')?SessionProxy::GetValue('login_fail'):0;
			$loginFail++;
			
			if($loginFail == 1) {
				$savedPost = serialize(Request::GetAllPost(false));
				$savedGet  = serialize(Request::GetAllGet(false));
				$savedFile = serialize($_FILES);
				
				SessionProxy::SetValue('login_fail_saved_post',$savedPost);
				SessionProxy::SetValue('login_fail_saved_get', $savedGet);
				SessionProxy::SetValue('login_fail_saved_file',$savedFile);
			}
			
			Router::SaveUrl($param);
			
			$url = isset($param['redirectUrlForRestrictedAccess'])?$param['redirectUrlForRestrictedAccess']:Router::GenerateUrl('redirectMainSite',array());

			if($this->renderer == 'ajax') {
			    $this->content = "document.location.href='$url'";
			}else{
				$msg = Registry::Exists('authMsg')?Registry::Get('authMsg'):$this->t('Nie posiadasz uprawnień do oglądania tej strony');
			    $this->AddRedirectInfo($msg,'ok',$url,0);
			}

			
			return true;
		};
	}

	

	

}
